﻿using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Chat;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;

namespace AI.Common
{
    public class ChatHelper
    {
        private readonly IChatClient _chatClient;
        private readonly List<ChatMessage> _chatHistory = new();
        public const string ModelName = "gemma3:27b";

        private ChatHelper(IChatClient chatClient)
        {
            _chatClient = chatClient;
        }

        // Factory with optional connection test
        public static async Task<ChatHelper> CreateAsync(bool testConnection = true)
        {
            var client = AIFactory.CreateOpenAiClient();
            var chatClient = client.GetChatClient(ModelName).AsIChatClient();
            var helper = new ChatHelper(chatClient);
            if (testConnection)
            {
                await helper.Connection();
                helper.ClearHistory(); // remove test conversation so it won't pollute subsequent system prompt
            }
            return helper;
        }

        public void ClearHistory() => _chatHistory.Clear();

        public void SetPrompt(string prompt)
        {
            // Ensure system prompt is first message only
            if (_chatHistory.Count == 0 || _chatHistory[0].Role != ChatRole.System)
            {
                _chatHistory.Insert(0, new ChatMessage(ChatRole.System, prompt));
            }
            else
            {
                _chatHistory[0] = new ChatMessage(ChatRole.System, prompt);
            }
        }

        public async Task<string> SendPromptAndRecive(string userPrompt, bool allowPrintLog = true)
        {
            _chatHistory.Add(new ChatMessage(ChatRole.User, userPrompt));
            if (allowPrintLog) Logger.WriteLine("AI Response:");
            var sb = new StringBuilder();
            await foreach (var item in _chatClient.GetStreamingResponseAsync(_chatHistory))
            {
                if (allowPrintLog && !string.IsNullOrEmpty(item.Text)) Logger.Write(item.Text);
                if (!string.IsNullOrEmpty(item.Text)) sb.Append(item.Text);
            }
            var response = sb.ToString();
            _chatHistory.Add(new ChatMessage(ChatRole.Assistant, response));
            return response;
        }

        public async Task Connection()
        {
            try
            {
                Console.WriteLine("--------------------------------------------------");
                var testMessages = new List<ChatMessage>
                {
                    new(ChatRole.User, "测试：请回复 OK")
                };
                Console.WriteLine("连接中:");
                string testResponse = "";
                await foreach (var item in _chatClient.GetStreamingResponseAsync(testMessages))
                {
                    Console.Write(item.Text);
                    testResponse += item.Text;
                }
                Console.WriteLine();
                Console.WriteLine("✅ API连接测试完成: " + testResponse.Trim());
                Console.WriteLine("--------------------------------------------------");
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ API连接测试失败！错误: " + ex);
                throw;
            }
        }
    }
}